import { Service, Injectable } from 'cdjs-swiftjs-plug';

/**
 * 数据缓存服务
 */
@Injectable()
export default class CacheService implements Service {
  private store: any = {};

  /**
   * 获取某键值对应数据，如果不存在则拉取
   * @param key 数据键
   * @param fetchFn 数据拉取函数
   */
  public async ensure (key: string, fetchFn?: () => Promise<any>): Promise<any> {
    if (this.store[key]) {
      return this.store[key];
    } else if (fetchFn) {
      try {
        this.store[key] = await fetchFn();
        return this.store[key];
      } catch (e) {
        //
      }
    }
    return null;
  }
}
